<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float:right"
          type="primary"
          @click="handleSearchList()"
          size="small">
          查询搜索
        </el-button>
        <el-button
          style="float:right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="用户ID：">
            <el-input v-model="listQuery.id" class="input-width" placeholder="用户ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户等级：">
            <el-select v-model="listQuery.level" class="input-width" placeholder="全部" clearable>
              <el-option v-for="item in orderTypeOptions"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码：">
            <el-input v-model="listQuery.phone" class="input-width" placeholder="手机号码" clearable></el-input>
          </el-form-item>
          <el-form-item label="邀请者ID：">
            <el-input v-model="listQuery.befId" class="input-width" placeholder="邀请者ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户昵称：">
            <el-input v-model="listQuery.nickname" class="input-width" placeholder="用户昵称" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <div class="table-container">
      <el-table ref="flashTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="用户ID" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="openDetail(scope.row.id)">{{scope.row.id}}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="用户昵称" align="center">
          <template slot-scope="scope">{{scope.row.nickname}}</template>
        </el-table-column>
        <el-table-column label="用户头像" align="center">
          <template slot-scope="scope">
            <img class="userImg" :src="scope.row.icon" alt="">
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            label="用户等级">
            <template slot-scope="scope">
              {{scope.row.level | statusDec}}
              <i @click="show(scope.row)" class="el-icon-edit"></i>
            </template>
        </el-table-column>
        <el-table-column label="邀请人ID" align="center">
          <template slot-scope="scope">
            {{scope.row.befId}}
            <i @click="updateId(scope.row.id)" class="el-icon-edit"></i>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" align="center">
          <template slot-scope="scope">{{scope.row.phone}}</template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageIndex"
        :page-size="listQuery.pageSize"
        :page-sizes="[20,100]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      title="修改等级"
      :visible.sync="dialogVisible"
      width="30%"
      top="35vh"
      :before-close="closeDialog">
          <el-row type='flex' justify="center" align="middle">
            <span style="margin-right:10px;">用户等级</span>
            <el-select v-model="orderType" class="input-width" placeholder="全部" clearable>
              <el-option v-for="item in orderTypeOptions"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
    </el-dialog>
    <child ref="child" :detailDialog="detailDialog"/>
  </div>
</template>
<script>
  import {fetchList, updateStatus, deleteFlash, createFlash, updateFlash} from '@/api/flash';
  import { getUserList , userUpdate , updateBefId} from '@/api/user'
  import {formatDate} from '@/utils/date';
  import child from './child'

  const defaultListQuery = {
    pageIndex: 1,
    pageSize: 20,
    id:'',
    level:'',
    phone:'',
    befId:'',
    nickname:''
  };
  const defaultFlashPromotion = {
    id: null,
    title: null,
    startDate: null,
    endDate: null,
    status: 0
  };
  export default {
    name: 'flashPromotionList',
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        dialogVisible: false,
        detailDialog: false,
        flashPromotion: Object.assign({}, defaultFlashPromotion),
        isEdit: false,
        tableSortArr:[],
        orderTypeOptions:[
          {name:'丽人',value:0},
          {name:'伊人',value:1},
          {name:'爱心大使',value:2},
          {name:'经销商',value:3}
        ],
        orderType:'',
        userItem:{},
        memberId:''
      }
    },
    created() {
        this.getList();
    },
    components:{
      child
    },
    filters: {
      statusDec(e) {
        if (e == 0) {
          return '丽人';
        } else if (e == 1) {
          return '伊人';
        } else if (e == 2) {
          return '爱心大使';
        }else if (e == 3 || e == 4) {
          return '经销商';
        }
      },
      formatDate(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd')
      }
    },
    methods: {
      // 确认修改
      save(){
        this.dialogVisible = false
        userUpdate(Object.assign(this.userItem,{level:this.orderType})).then(res=>{
          console.log(res)
          if(res.code == 200){
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
            this.getList();
          }else{
            this.$message.error(res.message)
          }
        })
      },
      // 修改邀请人ID
      updateId(id){
        this.$prompt('请输入邀请人Id', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]*$/,
          inputErrorMessage: '请输入数字'
        }).then(({ value }) => {
          let data = {
            befId:value,
            id
          }
          updateBefId(data).then(res=>{
            if(res.code == 200 && res){
              this.$message({
                type: 'success',
                message: '修改成功!'
              });
              this.getList();
            }else{
              console.log(res)
              // this.$message.error(res)
            }
          })
        }).catch(() => {
                 
        });
      },
      // 修改等级
      show(e){
        console.log(e)
        this.userItem = e
        this.orderType = e.level
        this.dialogVisible = true
      },
      // 关闭弹框
      closeDialog(){
        this.dialogVisible = false
        this.detailDialog = false
      },
      // 打开详情
      openDetail(id){
        this.$refs.child.pushId(id)
        this.detailDialog = true
      },
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageIndex = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageIndex = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageIndex = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.flashPromotion = Object.assign({},defaultFlashPromotion);
      },
      handleShowSessionList() {
        this.$router.push({path: '/sms/flashSession'})
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要修改该状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id, {status: row.status}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该活动?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteFlash(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        });
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        this.flashPromotion = Object.assign({},row);
      },
      handleDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.isEdit) {
            updateFlash(this.flashPromotion.id,this.flashPromotion).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          } else {
            createFlash(this.flashPromotion).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          }
        })
      },
      handleSelectSession(index,row){
        this.$router.push({path:'/sms/selectSession',query:{flashPromotionId:row.id}})
      },
      getList() {
        this.listLoading = true;
        getUserList(this.listQuery).then(response => {
          console.log(response)
          this.listLoading = false;
          this.list = response.list;
          this.total = response.total;
          this.tableSortArr = response.list.map(item => ({value: item.sort, isEdit: false}))
        });
      }
    }
  }
</script>
<style scoped>
  .userImg{
    width: 40px;
    height: 40px;
  }
</style>


